// Date:   Sun Nov 10 14:36:57 2024
// Mail:   lunar_ubuntu@qq.com
// Author: https://github.com/xiaoqixian

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    let b = match num_str.find('(') {
        None => panic!("invalid num_str: {num_str}"),
        Some(b) => b
    };
    let n = num_str.len();
    let base = match num_str[(b+1)..(n-1)].parse::<u32>() {
        Ok(b) => b,
        Err(_) => panic!("invalid base: {}", &num_str[(b+1)..(n-1)])
    };

    let (mut num, _) = num_str[..b].chars()
        .rev()
        .fold((0u32, 1), |(res, b), digit| {
            let d = match digit.to_digit(base) {
                None => panic!("invalid digit {digit} in base {base}"),
                Some(d) => d
            };
            (res + d * b, b * base)
        });

    let mut res = String::new();
    while num > 0 {
        res.push(char::from_digit(num % to_base, to_base).unwrap());
        num /= to_base;
    }
    res.chars().rev().collect()
}
